<template>
  <j-modal
    :maskClosable="false"
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <template slot="footer">
      <a-button key="back" @click="handleCancel">关闭</a-button>
      <a-button  @click="handleOk()" type="primary">确定</a-button>
      <a-button  v-has="'ReceivablesOperationModal:okAndPrint'" v-if='da.type == 1'  @click="print()" ghost type="primary">确定并打印</a-button>
    </template>
    <a-spin :spinning="confirmLoading">

      <a-form :form="form">
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="合同信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag v-decorator="['leaseContractId', validatorRules.leaseContractId]" :disabled="isDisabled"
                                   :async="true"  dict="zcgl_lease_contract_info,contract_num,id" @change="changeLease"/>
            </a-form-item>
          </a-col>

          <a-col v-if="!isReadOnly" :xs="24" :sm="12">
            <a-form-item label="资产信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag v-decorator="['assetId', validatorRules.assetId]" :disabled="isDisabled"
                                   @change="selectSub"
                                   :async="true" dict="zcgl_asset_info,asset_name,id"/>
            </a-form-item>
          </a-col>

          <a-col v-if="!isReadOnly" :xs="24" :sm="12">
          <a-form-item label="资产明细" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-search-select-tag
              :trigger-change="true"
              v-decorator="['assetSubIds', validatorRules.assetSubIds]"
              :dictOptions="searchOptions"
              :disabled="isDisabled"
              placeholder=""/>
          </a-form-item>
          </a-col>

          <a-col v-if="!isReadOnly" :xs="24" :sm="12">
            <a-form-item label="客户信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag v-decorator="['customerId', validatorRules.customerId]" :disabled="isDisabled"
                                   :async="true"    dict="zcgl_customer_info,name,id"/>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12">
            <a-form-item label="款项说明" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['paymentInstructions', validatorRules.paymentInstructions]" :disabled="isDisabled"
                                 :trigger-change="true" dictCode="payment_instructions" placeholder="请选择款项说明"></j-dict-select-tag>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12">
            <a-form-item label="开始日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择开始日期" v-decorator="['startTime', validatorRules.startTime]" :disabled="isDisabled"
                      :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12">
            <a-form-item label="结束日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择结束日期" v-decorator="['endTime', validatorRules.endTime]" :disabled="isDisabled"
                      :trigger-change="true" style="width: 100%"/>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12">
          <a-form-item label="应收金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input-number v-decorator="['amountMoney']" :disabled="isDisabled"  style="width: 100%"/>
          </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12">
            <a-form-item label="未收金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['unAmountMoney']" :disabled="isDisabled"  style="width: 100%"/>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12" v-if='da.type == 1'>
            <a-form-item label="预存金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['amountDeposited']" :disabled="isDisabled" />
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12" v-if='da.type == 1'>
            <a-form-item label="收款金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['payeeAmount', validatorRules.payeeAmount]" :disabled="da.type == 2" placeholder="请输入收款金额" style="width: 100%"/>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12" v-if='da.type == 1'>
          <a-form-item label="支付方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-dict-select-tag type="list" v-decorator="['payType', validatorRules.payType]" :trigger-change="true" dictCode="pay_type" placeholder="请选择支付方式"/>
          </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12" v-if='da.type == 1'>
          <a-form-item label="收款日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-date placeholder="请选择收款日期" v-decorator="['receiptDate', validatorRules.receiptDate]" :trigger-change="true"
                    style="width: 100%"/>
          </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12" v-if='da.type == 1'>
          <a-form-item label="收款人" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-search-select-tag :async="true" v-decorator="['payeeBy']" dict="sys_user,realname,id" placeholder="请选择收款人" />
          </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12" v-if='da.type == 1'>
            <a-form-item label="付款人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag v-decorator="['paymentBy', validatorRules.paymentBy]" :trigger-change="true"
                                   :dictOptions="paymentByList" />
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12" v-if='da.type == 1'>
            <a-form-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-upload v-decorator="['attachment']"  :trigger-change="true"></j-upload>
            </a-form-item>
          </a-col>

          <a-col :span="24" v-if='da.type == 1'>
          <a-form-item label="收款说明" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
            <a-textarea v-decorator="['payeeRemark']" rows="4" placeholder="请输入收款说明"/>
          </a-form-item>
          </a-col>

          <a-col :span="24" v-if='da.type == 1'>
          <a-form-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
            <a-textarea v-decorator="['remark']"  :disabled="isDisabled" rows="4" placeholder="请输入备注"/>
          </a-form-item>
          </a-col>

        </a-row>
      </a-form>

      <a-tabs v-model="activeKey"  v-if='da.type == 2'><!--@change="handleChangeTabs"-->
        <a-tab-pane tab="拆费明细" :key="refKeys[0]" :forceRender="true">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="false"
            :columns="columns"
            :dataSource="dataSource"
            :maxHeight="300"
            :rowNumber="false"
            :rowSelection="false"
            :actionButton="false"
            @inputBlur="handleInputBlur"
            @valueChange="handleValueChange">

            <!--          <span  slot="action" slot-scope="text, record">-->
            <!--            <a @click="handleDelete(props)">删除</a>-->
            <!--          </span>-->

            <template v-slot:action="props">
              <span v-if="props.index > 0">
                <a @click="handleDelete(props)">删除</a>
                <a-divider type="vertical"/>
              </span>
              <a @click="handleAdd(props)">添加</a>
            </template>
          </j-editable-table>

        </a-tab-pane>

      </a-tabs>

      <!--      &lt;!&ndash; 子表单区域 &ndash;&gt;-->
      <!--      <j-editable-table :columns="columns" :dataSource="dataSource" width="100%">-->
      <!--        &lt;!&ndash; 定义插槽 &ndash;&gt;-->
      <!--        &lt;!&ndash; 这种定义插槽的写法是vue推荐的新版写法（https://cn.vuejs.org/v2/guide/components-slots.html#具名插槽），旧版已被废弃的写法不再支持 &ndash;&gt;-->
      <!--        &lt;!&ndash; 若webstorm这样写报错，请看这篇文章：https://blog.csdn.net/lxq_9532/article/details/81870651 &ndash;&gt;-->
      <!--        <template v-slot:action="props">-->
      <!--          <a @click="handleDelete(props)">删除</a>-->
      <!--        </template>-->
      <!--      </j-editable-table>-->
      <ReceivablesPrintSelectTemplate-modal ref="receivablesPrintSelectTemplateModal"
                                            @ok="receivablesPrintSelectTemplateModalOk"></ReceivablesPrintSelectTemplate-modal>
      <ReceivablesPrint-modal ref="receivablesPrintModal"
                                            @ok="receivablesPrintModalOk"></ReceivablesPrint-modal>
    </a-spin>
  </j-modal>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import pick from 'lodash.pick'
  import JDate from '@/components/jeecg/JDate'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
  import JEditableTable from '@/components/jeecg/JEditableTable'
  import { dateAdd, sortTimeKey, divTime } from '@/utils/util'
  import {
    VALIDATE_NO_PASSED,
    getRefPromise,
    validateFormAndTables,
    FormTypes,
    validateTables
  } from '@/utils/JEditableTableUtil'
  import { toll, demolitionFee } from '@/api/receivables'
  import { queryCustomerBalance } from '@/api/customer'
  import { AssetSubMixin } from '@/api/assetSubMixin'
  import JUpload from '@comp/jeecg/JUpload'
  import ReceivablesPrintSelectTemplateModal from './ReceivablesPrintSelectTemplateModal'
  import ReceivablesPrintModal from './ReceivablesPrintModal'

  export default {
    name: 'ReceivablesOperationModal',
    mixins: [AssetSubMixin],
    components: {
      ReceivablesPrintSelectTemplateModal,
      ReceivablesPrintModal,
      JEditableTable,
      JUpload,
      JDate,
      JDictSelectTag,
      JSearchSelectTag
    },
    data () {
      return {
        form: this.$form.createForm(this),
        title: '操作',
        paymentByList: [],
        width: 800,
        visible: false,
        isDisabled: true,
        model: {},
        da: {},
        receivablesId:'',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        confirmLoading: false,
        isReadOnly: false,
        validatorRules: {
          payeeAmount: {
            rules: [
              { required: true, message: '请输入收款金额!' }
            ]
          },
          assetSubIds: {
            rules: [
              { required: false, message: '请输入资产明细!' }
              // { validator: this.validateCode }
            ]
          },
          payType: {
            rules: [
              { required: true, message: '请输入支付方式!' }
            ]
          },
          receiptDate: {
            rules: [
              { required: true, message: '请选择收款日期!' }
            ]
          },
          paymentBy: {
            rules: [
              { required: true, message: '请选择付款人!' }
            ]
          }
        },
        // table
        refKeys: ['receivablesDetails'],
        tableKeys: ['receivablesDetails'],
        activeKey: 'receivablesDetails',
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'index',
            width: '10%',
            align: 'center',
            fixed: "left",
            customRender: (text, record, index) =>
              `${(this.ipagination.current - 1) * this.ipagination.pageSize + index + 1}`
          },
          {
            title: '开始日期',
            type: FormTypes.date,
            key: 'startDate',
            width: '25%',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
            customRender: function (text) {
              return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
            },
            align: 'center'
          },
          {
            title: '收款金额',
            type: FormTypes.inputNumber,
            key: 'amountMoney',
            width: '20%',
            placeholder: '请输入${title}',
            defaultValue: '',
            customRender: function (text) {
              return !text ? '0.00' : text.toFixed(2);
            },
            // validateRules: [{ required: true, message: '${title}不能为空' }],
            validateRules: [
              { required: true, message: '${title}不能为空' },
              { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '请输入零以上的数字' },
            ],
            align: 'center'
          },
          {
            title: '备注',
            type: FormTypes.input,
            key: 'remark',
            width: '25%',
            placeholder: '请输入${title}',
            defaultValue: '',
            align: 'center'
          },
          {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            align: 'center',
            width: '20%',
            type: FormTypes.slot, // 定义该列为 自定义插值列
            slotName: 'action' // slot 的名称，对应 v-slot 冒号后面和等号前面的内容
            // // align:"center",
            // // fixed:"right",
            // // width:147,
            // scopedSlots: { customRender: 'action' }
          }
        ],
        dataSource: [
          {
            startDate: '',
            amountMoney: 0,
            remark: ''
          }
        ]
      }
    },
    created () {
    },
    methods: {
      receivablesPrintModalOk(){

      },
      receivablesPrintSelectTemplateModalOk(printTemplateId,receivablesId,payeeAmount){
        debugger
        this.$refs.receivablesPrintModal.show(printTemplateId, receivablesId,payeeAmount)
        this.loadData()
      },
      print(){
        const that = this
        if (this.da.type == 1) {
          // 触发表单验证
          this.form.validateFields((err, values) => {
            if (!err) {
              that.confirmLoading = true
              let formData = Object.assign(this.model, values)
              // console.log('表单提交数据', formData)
              toll(formData).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                  that.confirmLoading = false
                  that.close()
                  //弹出打印模板选择
                  this.$refs.receivablesPrintSelectTemplateModal.show(null, this.receivablesId,formData.payeeAmount);
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.confirmLoading = false
                // that.close()
              })
            }
          })
        } else {
          validateTables([this.$refs.receivablesDetails]).then((all) => {

            let main = this.model
            main.demolitionFeeList = all[0].values
            demolitionFee(main).then((res) => {
              if (res.success) {
                this.$message.success(res.message)
                this.$emit('ok')
                this.confirmLoading = false
                this.close()
              } else {
                this.$message.warning(res.message)
              }
            }).finally(() => {
              this.confirmLoading = false
              // this.close()
            })
          }).catch((e = {}) => {
            // 判断表单验证是否未通过
            // if (e.error === VALIDATE_NO_PASSED) {
            //   // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            //   this.activeKey = e.index == null ? this.activeKey : (e.index + 1).toString()
            // } else {
            //   console.error(e)
            // }
            if (e.error === VALIDATE_NO_PASSED) {
              console.log('未通过验证的实例下标:', e.index)
            } else {
              console.error('发生异常:', e)
            }
          })
        }
      },
      getAllTable () {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      handleInputBlur(props){
        const { type, row, column, value, target } = props
        var index = row.index
        if (column.key === 'amountMoney') {
          if (value != '' && parseFloat(value) > 0) {
            if (!this.dataSource[index-1].amountMoney && value == this.dataSource[index-1].amountMoney){
              return
            }
            if (this.dataSource.length == 1) {
              this.listAdd(1,"", parseFloat((this.model.unAmountMoney - value).toFixed(2)))
            } else {
            }
            this.dataSource[index-1].amountMoney = value.toFixed(2)
            this.splitDateMoney(index)
            this.sorts()
          } else {
            this.$message.warning('请输入大于0的金额！')
          }
          // this.sorts()
        }
      },
      handleValueChange (props) {
        const { type, row, column, value, target } = props
        var a = value
        var t = 0
        var index = row.index
        if (column.key === 'startDate') {
          t = -1
          if (divTime(value, this.model.endTime) <= 0) {
            this.$message.warning('日期不能在合同结束日期之后')
          } else if (divTime(this.model.startTime, value) <= 0) {
            // a = this.model.startTime
            this.$message.warning('日期不能在合同开始日期之前')
          } else {
            if (!this.listRepeat('startDate', value)) {
              if (index == 1) {
                index = 2
                this.listAdd(1, value, 0)
              } else {
                this.dataSource[index - 1].startDate = value
              }
            } else {
              this.$message.warning('日期已存在')
            }
          }
          this.sorts()
          this.splitAmountMoney()
        } else if (column.key === 'amountMoney') {
        } else {
          this.chageDate(index - 1, column.key, value)
        }
      },
      chageDate (index, key, value) {
        this.dataSource[index][key] = value
      },
      splitAmountMoney () {

        var svgMoney = this.model.unAmountMoney / divTime(this.model.startTime, this.model.endTime)
        var lastDate = this.model.endTime
        for (var i = this.dataSource.length - 1; i >= 0; i--) {
          if (this.dataSource[i].startDate != undefined && this.dataSource[i].startDate != '') {
            var day = divTime(this.dataSource[i].startDate, lastDate)
            this.dataSource[i].amountMoney = parseFloat((svgMoney * day).toFixed(2))
            lastDate = this.dataSource[i].startDate
          }
        }
      },
      //计算检测金额
      splitDateMoney (index) {

        let total =0;
        //循环到当前
        for (let i = 0; i < index; ) {
          if (this.dataSource[i].amountMoney == undefined || this.dataSource.amountMoney == "" || parseFloat(this.dataSource.amountMoney) <= 0){
            this.dataSource.splice(i, 1)
            continue
          }
          total = total + parseFloat(this.dataSource[i].amountMoney)
          i++
        }

        total = parseFloat(total.toFixed(2));
        let money = parseFloat(this.model.unAmountMoney.toFixed(2));
        if (total > money){
          this.$message.warning('拆分后的总金额错误')
          return
        } else if (total == money){
          if (this.dataSource.length > index){
            this.dataSource.splice(index, this.dataSource.length-index)
          }
        } else if (total < money){
          if (this.dataSource.length > index){
            for (let i = index; i < this.dataSource.length; ){
              if (this.dataSource[i].amountMoney == undefined || this.dataSource[i].amountMoney == "" || parseFloat(this.dataSource[i].amountMoney) <= 0.01){
                this.dataSource.splice(i, 1)
                continue
              }
              let newTotal = total + parseFloat(this.dataSource[i].amountMoney)
              if (parseFloat(newTotal.toFixed(2)) < money){
                i++
                total = newTotal
                continue
              }

              this.dataSource[i].amountMoney = (money - total).toFixed(2)
              let a = parseInt(i)+1;
              if (this.dataSource.length > a){
                this.dataSource.splice(a, this.dataSource.length-i)
              }
              total = newTotal
              break
            }
            if (total < money){
              this.listAdd(-1,"", parseFloat((money - total).toFixed(2)))
            }
          } else {
            this.listAdd(-1,"",  parseFloat((money - total).toFixed(2)))
          }
        }
        this.calculationDate()
      },
      //根据金额计算日期
      calculationDate(){
        //保存总共的金额
        let total =0;
        //总共有多少天
        let totalDay = divTime(this.model.startTime, this.model.endTime)
        //平均每天的金额
        let svgMoney = this.model.unAmountMoney / totalDay
        for (let i = 0; i < this.dataSource.length;i++){
          if (i == 0){
            this.dataSource[0].startTime = this.model.startTime
          } else {
            //根据总金额和每天的金额，计算多少天
            let day = total/svgMoney
            this.dataSource[i].startDate = dateAdd ("d", day+1, this.model.startTime)
          }
          total = total + parseFloat(this.dataSource[i].amountMoney)
          this.dataSource[i].index = i+1
        }
      },
      sorts () {
        //根据日期排序
        this.dataSource = sortTimeKey(this.dataSource, 'startDate')
        this.dataSource.forEach(function (item, index) {
          item.index = index + 1
        })
      },
      listAdd (index, startDate, amountMoney) {
        if (index >= 0){
          this.dataSource.splice(index, 0, { index: index, startDate: startDate, amountMoney: parseFloat(amountMoney).toFixed(2)})
        } else {

          this.dataSource.push({ startDate: startDate, amountMoney: parseFloat(amountMoney).toFixed(2)})
        }
      },
      listDel (index) {
        this.dataSource.splice(index, 1)
      },
      listRepeat (key, value) {
        var bool = false
        for (var i = 0; i < this.dataSource.length; i++) {
          if (this.dataSource[i][key] == value) {
            bool = true
            break
          }
        }
        return bool
      },
      /* a 标签的点击事件，删除当前选中的行 */
      handleDelete (props) {
        let { rowId, target, index } = props
        if (this.dataSource.length > 1) {
          this.listDel(index)
        } else {
          this.$message.warning('最后一条数据不能删除')
        }
        this.splitAmountMoney()
        this.sorts()
      },
      handleAdd (props) {
        let { rowId, target, index } = props
        this.listAdd(index + 1, '', 0)
        this.sorts()
      },
      show (title, record, type) {
        let that = this
        this.confirmLoading = false
        this.da.type = type
        this.title = title
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.paymentByList = []
        this.receivablesId=record.id;
        if (this.model.customerId) {
          let a = this.model.customerId.split(',')
          let b = this.model.customerId_dictText.split(',')
          a.forEach((item, index) => {
            that.paymentByList.push({'value': item, 'text': b[index] })
          })
          this.model.paymentBy = a[0]
        }
        if (this.model.leaseContractId) {
          this.isReadOnly = true
        } else {
          this.isReadOnly = false
        }
        this.selectSub1(this.model.assetId, this.model.assetSubIds)
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'paymentBy', 'payeeRemark', 'leaseContractId', 'attachment', 'unAmountMoney', 'assetId', 'customerId', 'paymentInstructions', 'amountMoney', 'payStatus', 'payType', 'startTime', 'endTime', 'receiptDate', 'remark', 'createBy', 'createTime', 'updateTime', 'updateBy'))
        })
        this.validatorRules.payeeAmount.rules[0].required = false
        if (type == 2) {
          this.dataSource = []
          this.dataSource.push({ index: 1, startDate: this.model.startTime, amountMoney: this.model.unAmountMoney })
        } else if (type == 1){
          this.validatorRules.payeeAmount.rules[0].required = true
          queryCustomerBalance({ customerId: that.model.customerId, leaseContractId: that.model.leaseContractId }).then((res) => {
            if (res.success) {
              if (res.result && res.result.balance){
                // let payeeAmount = (parseFloat(record.unAmountMoney)- parseFloat(res.result.balance)).toFixed(2);
                // that.form.setFieldsValue({ amountDeposited: res.result.balance, payeeAmount: payeeAmount })
                that.form.setFieldsValue({ amountDeposited: res.result.balance})
              } else {
                that.form.setFieldsValue({ amountDeposited: 0})
              }
            }
          })
        }
      },
      cancel (key) {
        let target = this.data.filter(item => item.key === key)[0]
        target.editable = false
      },
      handleChange (value, key, column) {
        const newData = [...this.data]
        const target = newData.filter(item => key === item.key)[0]
        if (target) {
          target[column] = value
          this.data = newData
        }
      },

      add () {
        this.edit({})
      },
      edit (record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'leaseContractId', 'assetId', 'payeeRemark', 'unAmountMoney', 'attachment', 'customerId', 'paymentInstructions', 'amountMoney', 'payStatus', 'payType', 'startTime', 'endTime', 'receiptDate', 'remark', 'createBy', 'createTime', 'updateTime', 'updateBy'))
        })
      },
      close () {
        this.$emit('close')
        this.visible = false
      },
      handleOk () {
        const that = this
        if (this.da.type == 1) {
          // 触发表单验证
          this.form.validateFields((err, values) => {
            if (!err) {
              that.confirmLoading = true
              let formData = Object.assign(this.model, values)
              // console.log('表单提交数据', formData)
              toll(formData).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                  that.confirmLoading = false
                  that.close()
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.confirmLoading = false
                // that.close()
              })
            }
          })
        } else {
          validateTables([this.$refs.receivablesDetails]).then((all) => {

            let main = this.model
            main.demolitionFeeList = all[0].values
            demolitionFee(main).then((res) => {
              if (res.success) {
                this.$message.success(res.message)
                this.$emit('ok')
                this.confirmLoading = false
                this.close()
              } else {
                this.$message.warning(res.message)
              }
            }).finally(() => {
              this.confirmLoading = false
              // this.close()
            })
          }).catch((e = {}) => {
            // 判断表单验证是否未通过
            // if (e.error === VALIDATE_NO_PASSED) {
            //   // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            //   this.activeKey = e.index == null ? this.activeKey : (e.index + 1).toString()
            // } else {
            //   console.error(e)
            // }
            if (e.error === VALIDATE_NO_PASSED) {
              console.log('未通过验证的实例下标:', e.index)
            } else {
              console.error('发生异常:', e)
            }
          })
        }
      },
      handleCancel () {
        this.close()
      },
      popupCallback (row) {
        this.form.setFieldsValue(pick(row, 'leaseContractId', 'assetId', 'payeeRemark', 'customerId', 'paymentInstructions', 'amountMoney', 'payStatus', 'payType', 'startTime', 'endTime', 'receiptDate', 'remark', 'createBy', 'createTime', 'updateTime', 'updateBy'))
      },

    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>